import axios from "axios";
import { MessageBox } from "element-ui";
//  // 环境的切换
if (process.env.NODE_ENV == "development") {
  // 测试环境使用development环境
  axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
} else if (process.env.NODE_ENV == "local") {
  // 本地开发使用local环境
  axios.defaults.baseURL = "/api";
} else {
  axios.defaults.baseURL = "/";
}

// 请求超时时间
axios.defaults.timeout = 30000;

// post请求头
axios.defaults.headers.post["Content-Type"] = "application/json";
// put请求头
axios.defaults.headers.put["Content-Type"] = "application/json";

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断
    let { url } = config;
    const Authorization = localStorage.getItem("Authorization");
    if (url === "/admin-api/system/captcha/get-image") {
      // 账户设置页面，要用验证码
      delete config.headers.Authorization;
    } else if (Authorization) {
      config.headers.Authorization = "Bearer " + Authorization;
    }
    return config;
  },
  (error) => {
    console.log(error, "request error");
    return Promise.error(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    let code = Number(response.data?.data?.code || response.data?.code)
    if (code === 1004053023 ) {
        // 项目管理-学生手机号码未注册
        response.data.data = {
            code: 1004053023
        }
        return Promise.resolve(response);
    } else if (code === 1004053024 ) {
        // 项目管理-学生未完成身份认证
        response.data.data = {
            code: 1004053024
        }
        return Promise.resolve(response);
    } else if (code === 1004053025 ) {
        response.data.data = {
            code: 1004053025
        }
        // 项目管理-该队员已个人/团队报名，无法再次参加
        return Promise.resolve(response);
    }  else if (
      (code == 401 && window.location.href !== "https://www.datarer.com/") ||
      code === 4002
    ) {
      let redirectUrl = window.location.href
      window.localStorage.clear();
      window.location.href = `/login?redirectUrl=${redirectUrl}`;
    } else {
      return Promise.resolve(response);
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    console.log(error)
    let errorCode = Number(
      error.response.data?.data?.code || error.response.data?.code
    );
    if (
      (errorCode == 401 &&
        window.location.href !== "https://www.datarer.com/text/") ||
      errorCode === 4002
    ) {
      MessageBox.alert("登录失效，请重新登录", "错误", {
        confirmButtonText: "确定",
        showClose: false,
        callback: () => {
          window.localStorage.clear();
          let redirectUrl = encodeURIComponent(window.location.href);
          window.location.href = `/login?redirectUrl=${redirectUrl}`;
        },
      });
      return Promise.reject(error.response);
    }
    console.log(error, "request error");
    // 对响应错误做点什么
    if(error.message.indexOf('timeout') > -1){   // 判断请求异常信息中是否含有超时timeout字符串
        MessageBox.alert("网络超时，请刷新后重试", "错误", {
            confirmButtonText: "确定",
            showClose: false,
            callback: () => {   
              window.location.reload()
            },
          });
      }
      return Promise.reject(error.response);
  }
);
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((res) => {
        // console.log(res, 'res.get')
        resolve(res.data);
      })
      .catch((err) => {
        // console.log(err, "get");
        reject(err.data);
      });
  });
}
export function deleteFun(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .delete(url, {
          params: params,
        })
        .then((res) => {
          // console.log(res, 'res.get')
          resolve(res.data);
        })
        .catch((err) => {
          // console.log(err, "get");
          reject(err.data);
        });
    });
  }

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .put(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
